using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace MouseKeyboardOperationSimulator
{
    public partial class KeyCaptureDialog : Form
    {
        private KeyboardHookManager keyboardHookManager;
        private List<string> capturedKeys = new List<string>();
        private string keyCombination = "";
        private bool isCapturing = false;
        private Label keyDisplayLabel;
        private Button okButton;

        public string CapturedKeyCombination { get; private set; }

        public KeyCaptureDialog()
        {
            SetupUI();
            InitializeKeyboardHook();
        }

        private void SetupUI()
        {
            this.Text = "按键记录";
            this.Size = new Size(400, 200);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            
            // 创建控件
            Label instructionLabel = new Label();
            instructionLabel.Text = "请按下要记录的按键组合：";
            instructionLabel.Location = new Point(20, 20);
            instructionLabel.Size = new Size(300, 20);
            
            keyDisplayLabel = new Label();
            keyDisplayLabel.Text = "等待按键...";
            keyDisplayLabel.Location = new Point(20, 50);
            keyDisplayLabel.Size = new Size(350, 30);
            keyDisplayLabel.Font = new Font(keyDisplayLabel.Font, FontStyle.Bold);
            keyDisplayLabel.TextAlign = ContentAlignment.MiddleLeft;
            
            okButton = new Button();
            okButton.Text = "确认";
            okButton.Location = new Point(100, 120);
            okButton.Size = new Size(75, 30);
            okButton.Enabled = false;
            okButton.Click += OkButton_Click;
            
            Button cancelButton = new Button();
            cancelButton.Text = "取消";
            cancelButton.Location = new Point(200, 120);
            cancelButton.Size = new Size(75, 30);
            cancelButton.Click += CancelButton_Click;
            
            // 添加控件到窗体
            this.Controls.Add(instructionLabel);
            this.Controls.Add(keyDisplayLabel);
            this.Controls.Add(okButton);
            this.Controls.Add(cancelButton);
            
            // 设置初始焦点
            this.ActiveControl = instructionLabel;
        }

        private void InitializeKeyboardHook()
        {
            keyboardHookManager = new KeyboardHookManager();
            keyboardHookManager.StartHook();
            keyboardHookManager.KeyPressed += KeyboardHookManager_KeyPressed;
        }

        private void KeyboardHookManager_KeyPressed(object sender, KeyEventArgs e)
        {
            if (isCapturing)
            {
                // 在UI线程上更新控件
                this.Invoke(new Action(() => {
                    UpdateKeyDisplay(e);
                }));
            }
        }

        private void UpdateKeyDisplay(KeyEventArgs e)
        {
            // 清空之前捕获的按键
            capturedKeys.Clear();
            
            // 添加当前按下的所有按键
            foreach (string key in e.PressedKeys)
            {
                // 特殊处理修饰键
                if (key == "Ctrl" || key == "Alt" || key == "Shift")
                {
                    capturedKeys.Add(key);
                }
            }
            
            // 添加当前按下的主键（非修饰键）
            if (e.KeyName != "Ctrl" && e.KeyName != "Alt" && e.KeyName != "Shift")
            {
                capturedKeys.Add(e.KeyName);
            }
            
            // 构造按键组合字符串
            keyCombination = "";
            if (capturedKeys.Count == 1)
            {
                // 单个按键
                keyCombination = capturedKeys[0];
            }
            else if (capturedKeys.Count >= 2)
            {
                // 组合键（修饰键+主键）
                string modifier = "";
                string mainKey = "";
                
                // 查找修饰键和主键
                foreach (string key in capturedKeys)
                {
                    if (key == "Ctrl" || key == "Alt" || key == "Shift")
                    {
                        modifier = key;
                    }
                    else
                    {
                        mainKey = key;
                    }
                }
                
                // 构造组合键字符串
                if (!string.IsNullOrEmpty(modifier) && !string.IsNullOrEmpty(mainKey))
                {
                    keyCombination = $"{modifier}+{mainKey}";
                }
                else if (!string.IsNullOrEmpty(mainKey))
                {
                    keyCombination = mainKey;
                }
                else
                {
                    keyCombination = capturedKeys[0];
                }
            }
            
            // 更新显示
            if (keyDisplayLabel != null)
            {
                keyDisplayLabel.Text = keyCombination;
            }
            
            // 启用确认按钮
            if (okButton != null)
            {
                okButton.Enabled = !string.IsNullOrEmpty(keyCombination);
            }
        }

        private void OkButton_Click(object sender, EventArgs e)
        {
            CapturedKeyCombination = keyCombination;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            isCapturing = true;
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            isCapturing = false;
            // 停止键盘钩子
            if (keyboardHookManager != null)
            {
                keyboardHookManager.StopHook();
            }
            base.OnFormClosed(e);
        }
    }
}